﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using DuocThaiBinh.HtmlHelpers.ExportToExcel;
using Newtonsoft.Json;
using PagedList;

namespace DuocThaiBinh.Controllers
{
    public class ThanhToanController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        //
        // GET: /ThanhToan/
        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public ActionResult Index(string txtSearch, string dtFrom, string dtTo, int? page)
        {
            List<ThanhToan> thanhtoans = null;
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID);
            foreach (var khachhang in khachhangs)
            {
                var temp = db.ThanhToans.Include(t => t.DVCC).Where(p => p.TypeOfPurchace == "DVCC").ToList();
                if (!string.IsNullOrEmpty(txtSearch))
                {
                    temp = temp.Where(p => p.DVCC.MaDVCC.ToLower().Equals(txtSearch.ToLower())).ToList();
                }
                DateTime dtFromout;
                if (!string.IsNullOrEmpty(dtFrom) && DateTime.TryParse(dtFrom, out dtFromout))
                {
                    temp = temp.Where(p => p.Date >= Util.ConvertObjectToDateTime(dtFromout)).ToList();
                }
                DateTime dtToout;
                if (!string.IsNullOrEmpty(dtFrom) && DateTime.TryParse(dtTo, out dtToout))
                {
                    temp = temp.Where(p => p.Date <= Util.ConvertObjectToDateTime(dtToout)).ToList();
                }

                if(temp != null)
                {
                    if(thanhtoans != null)
                    {
                        thanhtoans = temp;
                    }
                    else
                    {
                        thanhtoans.AddRange(temp);
                    }
                }
            }
            
            int pageSize = 50;
            int pageNumber = (page ?? 1);
            return View(thanhtoans.OrderByDescending(p => p.ID).ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "Administrator,StaffXuatKho,Staff")]
        public ActionResult IndexKH()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public JsonResult IndexKH(int page, int rows, string sidx, string sord, string from, string to, string filters, bool _search)
        {
            List<ThanhToan> _thanhtoans = null;
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID);
            foreach (var khachhang in khachhangs)
            {
                var temp = db.ThanhToans.OrderByDescending(p => p.ID).Where(p => p.KhachHang.MaKH != null && p.TypeOfPurchace == "KH" && p.ID_KH == khachhang.ID);

                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.Date >= Util.ConvertObjectToDateTime(from));
                }
                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.Date <= Util.ConvertObjectToDateTime(to));
                }

                if (temp != null)
                {
                    if (_thanhtoans == null)
                    {
                        _thanhtoans = temp.ToList();
                    }
                    else
                    {
                        _thanhtoans.AddRange(temp.ToList());
                    }
                }
            }

            var thanhtoans = _thanhtoans as IEnumerable<ThanhToan>;
            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                        case "TenKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.TenKH.ToLower().Contains(data.ToLower())); break;
                        //case "DiaChiKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.DiaChiKH.ToLower().Contains(data.ToLower())); break;
                        default: thanhtoans.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }
            var count = thanhtoans.Count<ThanhToan>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = thanhtoans.Skip(rows * (page - 1)).Take(rows).ToList();


            return Json(new
            {
                page = page,
                total = total,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.KhachHang.MaKH, x.KhachHang.TenKH, x.KhachHang.DiaChiKH, x.Price, x.Date })
            }, JsonRequestBehavior.AllowGet);
        }

        public ExcelResult ExportThanhToan(string sidx, string sord, string from, string to, string masp, string filter, bool search)
        {
            List<ThanhToan> _thanhtoans = null;
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID);
            foreach (var khachhang in khachhangs)
            {
                var temp = db.ThanhToans.OrderByDescending(p => p.ID).Where(p => p.TypeOfPurchace == "KH" && p.ID_KH == khachhang.ID);
                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.Date >= Util.ConvertObjectToDateTime(from));
                }
                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.Date <= Util.ConvertObjectToDateTime(to));
                }

                if(temp != null)
                {
                    if (_thanhtoans == null)
                    {
                        _thanhtoans = temp.ToList();
                    }
                    else
                    {
                        _thanhtoans.AddRange(temp.ToList());
                    }
                }
            }

            var thanhtoans = _thanhtoans as IEnumerable<ThanhToan>;

            if (search)
            {
                FiltersJq f = (!search || string.IsNullOrEmpty(filter)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filter);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                        case "TenKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.TenKH.ToLower().Contains(data.ToLower())); break;
                        case "DiaChiKH": thanhtoans = thanhtoans.Where(p => p.KhachHang.DiaChiKH.ToLower().Contains(data.ToLower())); break;
                        default: thanhtoans.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                    }
                }
            }

            decimal tongthanhtoan = 0;
            DataTable tablenew = new DataTable("thanhtoan");
            tablenew.Columns.Add("Khách hàng");
            tablenew.Columns.Add("Địa chỉ");
            tablenew.Columns.Add("Ngày thanh toán");
            tablenew.Columns.Add("Tiền thanh toán", typeof(double));

            foreach (ThanhToan thanhtoan in thanhtoans)
            {
                DataRow newrow = tablenew.NewRow();
                newrow["Khách hàng"] = thanhtoan.KhachHang.TenKH;
                newrow["Địa chỉ"] = thanhtoan.KhachHang.DiaChiKH;
                DateTime dt = Convert.ToDateTime(thanhtoan.Date);
                newrow["Ngày thanh toán"] = dt.ToString("dd/MM/yyyy");
                var tongtt = thanhtoan.Price;
                newrow["Tiền thanh toán"] = tongtt;
                tongthanhtoan += Util.ConvertCurrencyToMoney(tongtt);
                tablenew.Rows.Add(newrow);
            }
            DataRow newrow1 = tablenew.NewRow();
            newrow1["Ngày thanh toán"] = "Tổng :";
            newrow1["Tiền thanh toán"] = Util.ConvertDecimaToCurrency(tongthanhtoan);
            tablenew.Rows.Add(newrow1);
            string excelFilename = "Thống kê thanh toán " + DateTime.Now.ToString("dd/MM/yyyy") + ".xlsx";
            string[] cellStyle = new[] { "Text", "Text", "Text", "Double" };
            var stream = CreateExcelFile.CreateExcelDocument(tablenew, excelFilename);
            return new ExcelResult()
            {
                FileName = excelFilename,
                Stream = stream
            };
        }


        //
        // GET: DVCC thanh toán
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Create()
        {
            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "MaDVCC");
            //ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "TenKH");
            return View();
        }

        //
        // POST: DVCC thanh toán
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost]
        public ActionResult Create(ThanhToan thanhtoan)
        {
            if (ModelState.IsValid)
            {
                thanhtoan.TypeOfPurchace = "DVCC";
                db.ThanhToans.Add(thanhtoan);
                //Update lai tong no
                var idDvcc = thanhtoan.ID_DVCC;
                DVCC dvcc = db.DVCCs.Find(idDvcc);
                if (dvcc != null)
                {
                    var tienThanhToan = Util.ConvertCurrencyToMoney(thanhtoan.Price);
                    var tongNoCu = Util.ConvertCurrencyToMoney(dvcc.TongNo);
                    var tongNoMoi = tongNoCu - tienThanhToan;
                    string strTongNoMoi = Util.ConvertDecimaToCurrency(tongNoMoi);
                    dvcc.TongNo = strTongNoMoi;
                    db.Entry(dvcc).State = EntityState.Modified;
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "MaDVCC", thanhtoan.ID_DVCC);
            //ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "TenKH", thanhtoan.ID_KH);
            return View(thanhtoan);
        }
        // GET: KH thanh toán
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult CreateKH()
        {
            //ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC");
            ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "MaKH");
            return View();
        }

        //
        // POST: DVCC thanh toán
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        [HttpPost]
        public ActionResult CreateKH(ThanhToan thanhtoan)
        {
            if (ModelState.IsValid)
            {
                thanhtoan.TypeOfPurchace = "KH";
                db.ThanhToans.Add(thanhtoan);
                //Update lai tong no
                var idKH = thanhtoan.ID_KH;
                KhachHang khachHang = db.KhachHangs.Find(idKH);
                if (khachHang != null)
                {
                    //var tienThanhToan = Convert.ToDecimal(thanhtoan.Price.Replace(",", ""));
                    var tienThanhToan = Util.ConvertCurrencyToMoney(thanhtoan.Price);
                    var tongNoCu = Util.ConvertCurrencyToMoney(khachHang.TongNo);
                    var tongNoMoi = tongNoCu - tienThanhToan;
                    string strTongNoMoi = Util.ConvertDecimaToCurrency(tongNoMoi);
                    khachHang.TongNo = strTongNoMoi;
                    db.Entry(khachHang).State = EntityState.Modified;
                }
                db.SaveChanges();
                return RedirectToAction("IndexKH");
            }

            //ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC", thanhtoan.ID_DVCC);
            ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "MaKH", thanhtoan.ID_KH);
            return View(thanhtoan);
        }

        //
        // GET: /ThanhToan/Edit/5
        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public ActionResult Edit(int id = 0)
        {
            ThanhToan thanhtoan = db.ThanhToans.Find(id);
            if (thanhtoan == null || thanhtoan.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC", thanhtoan.ID_DVCC);
            ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "TenKH", thanhtoan.ID_KH);
            return View(thanhtoan);
        }

        //
        // POST: /ThanhToan/Edit/5
        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        [HttpPost]
        public ActionResult Edit(ThanhToan thanhtoan)
        {
            KhachHang kh = db.KhachHangs.Find(thanhtoan.ID_KH);
            if(kh == null || kh.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return RedirectToAction("Index", "Home");
            }
            if (ModelState.IsValid)
            {
                db.Entry(thanhtoan).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC", thanhtoan.ID_DVCC);
            ViewBag.ID_KH = new SelectList(db.KhachHangs, "ID", "TenKH", thanhtoan.ID_KH);
            return View(thanhtoan);
        }

        //
        // GET: /ThanhToan/Delete/5
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Delete(int id = 0)
        {
            ThanhToan thanhtoan = db.ThanhToans.Find(id);
            if (thanhtoan == null || thanhtoan.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            var idKH = thanhtoan.ID_KH;
            KhachHang khachHang = db.KhachHangs.Find(idKH);
            if (khachHang != null)
            {
                var tienThanhToan = Util.ConvertCurrencyToMoney(thanhtoan.Price);
                var tongNoCu = Util.ConvertCurrencyToMoney(khachHang.TongNo);
                var tongNoMoi = tongNoCu + tienThanhToan;
                string strTongNoMoi = Util.ConvertDecimaToCurrency(tongNoMoi);
                khachHang.TongNo = strTongNoMoi;
                db.Entry(khachHang).State = EntityState.Modified;
            }

            db.ThanhToans.Remove(thanhtoan);
            db.SaveChanges();
            return RedirectToAction("IndexKH");
        }

        ////
        //// POST: /ThanhToan/Delete/5
        //[Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        //[HttpPost, ActionName("Delete")]
        //public ActionResult DeleteConfirmed(int id)
        //{
        //    ThanhToan thanhtoan = db.ThanhToans.Find(id);
        //    db.ThanhToans.Remove(thanhtoan);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}